import os, sys, shutil, stat
from time import time
from lib.coverage import CoverageReport, outputReportAsJSON
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="A PureCoverage text file")
parser.add_option("-o", "--output", dest="output",
                  help="The path of a directory to produce the report in")
(options, args) = parser.parse_args()

# check for the file we're parsing
if not options.filename:
  print "no input file. try --help"
  sys.exit(0)

# check for an output dir. If it's not specified, use cwd plus a timestamp 
output = options.output
if not output:
  output = "coverage-%s" % int(time())
  output = os.path.join(sys.path[0], output)

if os.path.exists(output):
  if not os.path.isdir(output):
    print "output path exists, but isn't a directory"
    sys.exit(0)
else:
  os.makedirs(output)

resources = os.path.join(sys.path[0], "resources")
# copy our index.html page
shutil.copy(os.path.join(resources, "index.html"),
            os.path.join(output, "index.html"))
# copy our source highlight sheet
shutil.copy(os.path.join(resources, "source.css"),
            os.path.join(output, "source.css"))

# copy YUI over, then remove .svn dirs
if not os.path.exists(os.path.join(output, "yui")):
  shutil.copytree(os.path.join(resources, "yui", "build"),
                  os.path.join(output, "yui"))

# Broken on windows for some reason
#for root, dirs, files in os.walk(os.path.join(output, "yui"), topdown=False):
#  for name in files:
#    if root == ".svn":
#      os.chmod(os.path.join(root, name), stat.S_IWRITE)
#      os.remove(os.path.join(root, name))
#  for name in dirs:
#    if name == ".svn":
#      shutil.rmtree(os.path.join(root, name))

r = CoverageReport()
r.process(file(options.filename))

dataDir = os.path.join(output, "data")
if not os.path.exists(dataDir):
  os.mkdir(dataDir)
outputReportAsJSON(r, dataDir)

print output
print len(r.modules)
